﻿using DevExpress.ExpressApp.Security;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Domain.Services;
using YAPACS.BusinessObjects.Exams;
using YAPACS.Organizations;
using YAPACS.RisServer.Abstractions;
using YAPACS.Workflows;

namespace YAPACS.RisServer.Services;

public class AccountVerifyService(
    IRepository<ApplicationUser, Guid> userRepository,
    ICurrentUserOrganization currentUserOrganization,
    IExamPermissionService examPermissionService,
    SignInManager signInManager)
    : DomainService, IAccountVerifyService, ITransientDependency
{
    private readonly IRepository<ApplicationUser, Guid> _userRepository = userRepository;
    private readonly ICurrentUserOrganization _currentUserOrganization = currentUserOrganization;
    private readonly IExamPermissionService _examPermissionService = examPermissionService;
    private readonly SignInManager _signInManager = signInManager;

    public async Task<WorkflowOutput> GetVerifyViewAsync()
    {
        var user = await _userRepository.GetAsync(_currentUserOrganization.UserId);
        var content = await Extensions.GetResourceStringAsync("Resources.Account.verify-view.json");
        return new WorkflowOutput
        {
            Success = true,
            Data = new
            {
                user.UserName,
            },
            ViewTitle = "确认用户",
            View = content,
            ViewWidth = "25%"
        };
    }

    public async Task<WorkflowOutput> VerifyAsync(string userName, string password, string permission = null, Exam exam = null, Func<bool, ApplicationUser, WorkflowOutput> func = null)
    {
        var authResult = _signInManager.AuthenticateByLogonParameters(new OrganizationLogonParameters(userName, password));
        if (authResult.Succeeded)
        {
            var user = await _userRepository.GetAsync(e => e.UserName == userName);
            var hasPermission = permission == null || user.GetUserPermissions().Select(e => e.Name).ToList().Contains(permission);
            if (func != null)
            {
                var result = func.Invoke(hasPermission, user);
                if (result.Success)
                {
                    return result;
                }
            }
            else
            {
                if (!hasPermission)
                {
                    return new WorkflowOutput
                    {
                        Success = false,
                        Error = "账号没有操作权限"
                    };
                }

                if (exam != null)
                {
                    await _examPermissionService.ValidateAsync(exam, user);
                }
            }
            return new WorkflowOutput()
            {
                Success = true
            };
        }
        else
        {
            return new WorkflowOutput()
            {
                Success = false,
                Error = "用户名或密码错误"
            };
        }
    }
}
